package com.joyxy;

import com.joyxy.core.RobotController;
import com.joyxy.core.ScreenCapture;
import com.joyxy.core.ImageMatcher;
import com.joyxy.config.GameConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 游戏自动化主程序
 * 使用Java Robot API在虚拟显示器中控制Windows游戏
 */
public class GameAutomation {
    private static final Logger logger = LoggerFactory.getLogger(GameAutomation.class);
    
    private final RobotController robotController;
    private final ScreenCapture screenCapture;
    private final ImageMatcher imageMatcher;
    private final GameConfig gameConfig;
    private final ScheduledExecutorService scheduler;
    
    private volatile boolean running = false;
    
    public GameAutomation() throws AWTException, IOException {
        logger.info("初始化游戏自动化系统...");
        
        this.robotController = new RobotController();
        this.screenCapture = new ScreenCapture();
        this.imageMatcher = new ImageMatcher();
        this.gameConfig = GameConfig.load("config/game-config.yaml");
        this.scheduler = Executors.newScheduledThreadPool(4);
        
        logger.info("游戏自动化系统初始化完成");
    }
    
    public static void main(String[] args) {
        try {
            // 检查显示器环境
            if (GraphicsEnvironment.isHeadless()) {
                logger.error("检测到无头环境，请确保Xvfb正在运行");
                System.exit(1);
            }
            
            GameAutomation automation = new GameAutomation();
            
            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(automation::shutdown));
            
            automation.start();
            
        } catch (Exception e) {
            logger.error("游戏自动化启动失败", e);
            System.exit(1);
        }
    }
    
    public void start() {
        logger.info("启动游戏自动化...");
        running = true;
        
        // 等待系统稳定
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        
        // 开始主循环
        scheduler.scheduleWithFixedDelay(this::gameLoop, 0, 1, TimeUnit.SECONDS);
        
        // 定期截图保存
        scheduler.scheduleWithFixedDelay(this::takeScreenshot, 10, 30, TimeUnit.SECONDS);
        
        logger.info("游戏自动化已启动");
        
        // 保持主线程运行
        try {
            while (running) {
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    private void gameLoop() {
        try {
            if (!running) return;
            
            // 获取当前屏幕截图
            Rectangle screenRect = new Rectangle(0, 0, 1920, 1080);
            var screenshot = screenCapture.capture(screenRect);
            
            if (screenshot == null) {
                logger.warn("截图失败，跳过本次循环");
                return;
            }
            
            // 检查游戏状态
            checkGameStatus(screenshot);
            
            // 执行自动化操作
            performAutomationTasks(screenshot);
            
        } catch (Exception e) {
            logger.error("游戏循环执行出错", e);
        }
    }
    
    private void checkGameStatus(java.awt.image.BufferedImage screenshot) {
        // 检查游戏是否在运行
        // 可以通过图像识别特定的游戏界面元素
        // 这里可以添加具体的游戏状态检测逻辑
        
        logger.debug("检查游戏状态...");
    }
    
    private void performAutomationTasks(java.awt.image.BufferedImage screenshot) {
        // 执行具体的自动化任务
        // 例如：点击按钮、移动鼠标、按键等
        
        // 示例：查找并点击特定图像
        var buttonLocation = imageMatcher.findImage(screenshot, "templates/start_button.png");
        if (buttonLocation != null) {
            logger.info("找到开始按钮，执行点击");
            robotController.click(buttonLocation.x, buttonLocation.y);
        }
    }
    
    private void takeScreenshot() {
        try {
            if (!running) return;
            
            String filename = String.format("screenshot_%d.png", System.currentTimeMillis());
            var screenshot = screenCapture.captureAndSave(
                new Rectangle(0, 0, 1920, 1080),
                Paths.get("screenshots", filename)
            );
            
            if (screenshot != null) {
                logger.debug("保存截图: {}", filename);
            }
            
        } catch (Exception e) {
            logger.error("保存截图失败", e);
        }
    }
    
    public void shutdown() {
        logger.info("关闭游戏自动化系统...");
        running = false;
        
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
            try {
                if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                    scheduler.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduler.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
        
        logger.info("游戏自动化系统已关闭");
    }
} 